require('file')

function checkNpmPackage(tarballDir, extractDir)
    print('checkNpmPackage', tarballDir, extractDir)
    packageDir = extractDir..'/package'

    if directoryExists(packageDir) then
        print('Package Exist', packageDir)
        return true
    else
        print('Package Not Exist', packageDir)
        return false
    end
end

function extractTgz(tarballFilename, extractDir)
    print('extractTgz', tarballFilename, extractDir)
    
    ret = extractFile(tarballFilename, extractDir)
    print(ret)

    files = listDir(extractDir)
    tarfname = files[1]
    print(tarfname)
    for i = 1, #files do
        print(i, files[i])
    end
end

function downloadNpm(name)
    local dir = "../data"
    tarballDir = dir .. '/tarball/'
    extractDir = dir .. '/npm/' .. name
    tryCreateDir(dir)
    tryCreateDir(tarballDir)
    
    local fileUrl = "https://registry.npmmirror.com/" .. name
    local targetFileName = name .. ".json" -- 替换为想要保存的文件名

    npmJson = dir .. '/' .. targetFileName
    if fileExists(npmJson) then
        print(targetFileName .." exists")
    else
        print(targetFileName .. " not exists download it now")
        downloadFileWithCertUtil(fileUrl, npmJson)
    end

    local fileContent = readFile(npmJson)

    if fileContent then
        j = json.decode(fileContent)
        latest = j['dist-tags'].latest
        tarballUrl = j.versions[latest].dist.tarball
        tarballFilename = tarballDir .. '/' .. extract_url_filename(tarballUrl)
        downloadFileWithCertUtil(tarballUrl, tarballFilename)

        if checkNpmPackage(tarballDir, extractDir) then
            print('check npm ok')
        else
            print('check npm fail')
            extractTgz(tarballFilename, extractDir)
            extractFile(tarfname, extractDir)
        end

    else
        print("read file fail")
    end    
end

